/*
 * TimeoutBroker.cpp
 *
 *  Created on: 25/07/2014
 *      Author: migue
 */

#include "TimeoutBroker.h"
#include "../defines.h"

#include "../ipc/MemoriaCompartida.h"
#include "../ipc/Semaforo.h"

#define TAM_VAR		sizeof(unsigned int)

TimeoutBroker::TimeoutBroker(int numBroker) {
	_mc = new MemoriaCompartida(RUTA, ID_TIMEOOUT_BROKER(numBroker), TAM_VAR);
	_mtx = new Semaforo(RUTA, 1, ID_TIMEOOUT_BROKER(numBroker));
}

TimeoutBroker::~TimeoutBroker() {
	delete _mc;
	delete _mtx;
}


void TimeoutBroker::inicializar() {

	for (int i = 0 ; i < CANT_MAX_BROKERS ; ++i ) {
		MemoriaCompartida m(RUTA, ID_TIMEOOUT_BROKER(i+1), TAM_VAR);
		Semaforo s(RUTA, 1, ID_TIMEOOUT_BROKER(i+1) , true);

		s.inicializar(1);

		unsigned int valor = 0;
		m.escribir(0, (void*) &valor, TAM_VAR);
	}
}

void TimeoutBroker::destruir() {
	for (int i = 0 ; i < CANT_MAX_BROKERS; ++i) {
		MemoriaCompartida m(RUTA, ID_TIMEOOUT_BROKER(i+1), TAM_VAR);
		m.destruir();

		Semaforo::destruirSemaforo(RUTA, 1 ,ID_TIMEOOUT_BROKER(i+1));
	}
}

unsigned int TimeoutBroker::get() {
	unsigned int valor;

	_mtx->wait();

	_mc->leer(0, (void*) &valor, TAM_VAR);

	_mtx->signal();

	return valor;
}

void TimeoutBroker::set(unsigned int valor) {
	_mtx->wait();

	_mc->escribir(0, (void*) &valor, TAM_VAR);

	_mtx->signal();
}
